<?php
namespace app\admin\controller;

class Picture extends Admin {

	public $model;

	public function _initialize() {
		parent::_initialize();
		$this->model = D('api/album');
	}

	public function index() {
		$map['tmp'] = 1;

		//分页
		$num = 10; //每页显示多少数据
		$count = $this->model->where($map)->count();
		$max_page = ceil($count / $num);
		$new_page = I('get.page/d', 1);
		$new_page = $new_page > $max_page ? $max_page : $new_page;

		$list = $this->model->where($map)->page($new_page, $num)->order('sort desc,id desc')->select();
		$url = '?';
		foreach (I('get.', []) as $k => $v) {
			if ($k != 'page') {
				$url .= $k . '=' . $v . '&';
			}
		}
		return $this->fetch('index', [
			'list' => $list,
			'count' => $count,
			'max_page' => $max_page,
			'url' => $url,
		]);
	}

	public function create() {
		//创建相册
		$res = $this->model->where(['tmp' => 2])->find();
		if (!$res) {
			//创建相册
			$data = [
				'aname' => '未命名',
				'status' => '1',
				'update_time' => NOW_TIME,
				'tmp' => 2,
				'number' => 0,
			];
			$res = $this->model->add($data);
			$res = $this->model->where(['id' => $res])->find();
		}
		return $this->fetch('create', ['res' => $res]);
	}

	public function update() {
		//查询相册数据
		$res = $this->model->where(['id' => I('get.aid/d')])->find();
		if (!$res) {
			return $this->error('该相册不存在');
		}
		return $this->fetch('create', ['res' => $res]);
	}

	/**
	 * 更改相册状态
	 */
	public function setStatus() {
		$aid = I('post.aid/d');
		$status = I('post.status/d');

		if ($status == 1 || $status == 2) {
			$res = $this->model->where(['id' => $aid])->setField([
				'status' => $status,
				'update_time' => NOW_TIME,
			]);
			return json_encode([
				'status' => $res ? 'y' : 'n',
				'info' => '数据更新失败',
			]);
		} else {
			return json_encode([
				'status' => 'n',
				'info' => '参数错误',
			]);
		}
	}
	/**
	 * 相册删除
	 */
	public function delete() {
		//删除相册/图片
	}

	/**
	 * 查看图片
	 */
	public function pictureShow() {
		$map['album_id'] = I('get.aid/d');

		$mPicture = M('Picture');
		//分页
		$num = 12; //每页显示多少数据
		$count = $mPicture->where($map)->count();
		$max_page = ceil($count / $num);
		$new_page = I('get.page/d', 1);
		$new_page = $new_page > $max_page ? $max_page : $new_page;

		$list = $mPicture->where($map)->page($new_page, $num)->order('sort desc,id desc')->select();
		$url = '?';
		foreach (I('get.', []) as $k => $v) {
			if ($k != 'page') {
				$url .= $k . '=' . $v . '&';
			}
		}
		return $this->fetch('show', [
			'list' => $list,
			'count' => $count,
			'max_page' => $max_page,
			'url' => $url,
		]);
	}

	/**
	 * 删除图片
	 */
	public function delPicture() {
		$pid = I('post.pid/d');
		//查询图片地址
		$mPicture = M('picture');
		$res = $mPicture->where(['id' => $pid])->field('id,path,album_id')->find();
		$result = $mPicture->where(['id' => $res['id']])->delete();

		if ($result) {
			$this->model->where(['id' => $res['album_id']])->setDec('number');
			$key = 'Picture_' . $res['album_id'] . '_' . $res['id'] . '.png';
			$auth = new \Qiniu\Auth(C('AccessKey'), C('SecretKey'));
			$bucketMgr = new \Qiniu\Storage\BucketManager($auth);
			$r = $bucketMgr->delete(C('bucket'), $key);
			return json_encode([
				'status' => 'y',
				'info' => json_encode($r),
			]);
		} else {
			return json_encode([
				'status' => 'n',
				'info' => '删除失败',
			]);
		}

	}

	/**
	 * 保存提交
	 */
	public function technique() {
		if (IS_AJAX) {
			//判断是否上传缩略图
			$res = $this->model->where(['id' => I('post.aid/d')])->find();
			if (empty($res['img'])) {
				return json_encode([
					'status' => 'n',
					'info' => '相册缩略图没有上传',
				]);
			}

			//判断相册名称是否唯一
			$res = $this->model->where([
				'id' => ['neq', I('post.aid/d')],
				'aname' => ['eq', I('post.aname/s')],
			])->find();
			if ($res) {
				return json_encode([
					'status' => 'n',
					'info' => '相册名称已经存在！',
				]);
			}

			//验证
			$data = $this->model->validate(
				[
					'aname' => 'require|max:50',
					'sort' => 'number|egt:0',
				],
				[
					'aname.require' => '请填写相册名称',
					'aname.max' => '相册名称最大长度为50个字符',
					'sort.number' => '相册排序只能为数字',
					'sort.egt' => '排序的数字必须大于等于0',
				]
			)->create([
				'aname' => I('post.aname/s'),
				'update_time' => NOW_TIME,
			]);

			if (!$data) {
				return json_encode([
					'status' => 'n',
					'info' => $this->model->getError(),
				]);
			} else {
				$r = $this->model->where(['id' => I('post.aid')])
					->setField($data);
				return json_encode([
					'status' => $r ? 'y' : 'n',
					'info' => '数据库操作失败！',
				]);
			}
		}
	}

	/**
	 * 相册图片上传
	 */
	public function upload() {
		$auth = new \Qiniu\Auth(C('AccessKey'), C('SecretKey'));
		$upToken = $auth->uploadToken(C('bucket'));
		$uploadMgr = new \Qiniu\Storage\UploadManager();

		//新建图片条目
		$mPicture = M('picture');
		$data = [
			'pname' => I('post.name/s', '1'),
			'album_id' => I('post.aid/d'),
			'update_time' => NOW_TIME,
		];
		$add_id = $mPicture->add($data);
		$this->model->where(['id' => $data['album_id']])->setInc('number', 1);

		$key = 'Picture_' . $data['album_id'] . '_' . $add_id . '.png';
		list($ret, $err) = $uploadMgr->putFile($upToken, $key, $_FILES['file']['tmp_name']);

		if ($err) {
			return json_encode([
				'status' => 'n',
				'info' => '图片上传失败',
			]);
		} else {
			$data = [
				'path' => C('qn_url') . $ret['key'],
				'hash' => $ret['hash'],
			];

			$res = $mPicture->where(['id' => $add_id])->setField($data);
			return json_encode([
				'status' => $res ? 'y' : 'n',
				'info' => '数据库保存失败！',
			]);
		}
	}
}
